<template>
  <!--审核开题报告-->
  <div class="opening-report">
    <InnerBreadcrumb v-if="!idTip" v-model="indexKey" :path="breadPath" :showBack="true" />

    <div class="edu-page-warp" v-show="indexKey === 'MAIN'">
      <!--指定审核人 弹框-->
      <DesignatedDialog ref="designatedDialog" :designatedDialogVisible="dialogVisible" :selectedList="selectedData" @designated-submit="designatedSubmit" @designated-cancel="designatedCancel"></DesignatedDialog>

      <condition-card @reset="reset" @search="searchList" label-width="140px">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.graduationYear')">
              <el-date-picker class="search-item" :clearable="false" v-model="queryForm.grade" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.adminCollege')">
              <el-select v-model="queryForm.collegeId" filterable @change="handleCollegeChange" class="search-item" clearable>
                <el-option v-for="item in source.studentColleges" :key="item.collegeId" :label="item.collegeIdI18n" :value="item.collegeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.major')">
              <el-select v-model="queryForm.subjectId" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectOptions" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.reviewStatus')">
              <el-select v-model="queryForm.status" filterable class="search-item" clearable>
                <el-option v-for="item in source.statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectName')">
              <el-input v-model="queryForm.projectName" class="search-item" :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title">{{$t('graduationDesign.graduationDesignOpeningReport')}}</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <el-input v-model="queryForm.teacherNum" :placeholder="$t('graduationDesign.pleaseEnterWorkNumSearch')" style="width:300px" @keyup.enter.native="searchList" clearable>
              <i slot="suffix" class="el-icon-search" style="margin-top:10px;cursor:pointer" @click="searchList"></i>
            </el-input>
          </div>
          <div class="float-right">
            <el-button type="primary" @click="onDesignated" v-if="role === 'Academic'">{{$t('graduationDesign.designatedReviewer')}}</el-button>
            <el-button @click="onExport" v-loading.fullscreen.lock="loading" element-loading-text="Loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, .48)">{{$t('graduationDesign.exportPdf')}}</el-button>
          </div>
        </div>

        <edu-table ref="reviewReportTable" :url="url" @selection-change="handleSelectChange">
          <edu-table-column :label="$t('graduationDesign.graduationYear')" prop="grade" min-width="80"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectName')" prop="projectName" min-width="120"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.adminCollege')" prop="collegeI18n" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.major')" prop="subjectName" min-width="80"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.direction')" prop="directionName" min-width="80"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.student')" prop="studentName" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.tutor')" prop="teacherName" min-width="100"></edu-table-column>
          <edu-table-column label="指定审核人" min-width="110">
            <template slot-scope="scope">
              {{scope.row.approveId ? `${scope.row.approveName}(${scope.row.approveId})` : ''}}
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.reviewStatus')" min-width="100" v-if="role === 'Tutor'">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.firstStatus === 'WaitCommit'" type="info">{{$t('graduationDesign.draft')}}</el-tag>
              <el-tag v-else-if="scope.row.firstStatus === 'Process'" type="info">{{$t('graduationDesign.pendingReview')}}</el-tag>
              <el-tag v-else-if="scope.row.firstStatus === 'Reject'" type="danger">{{$t('graduationDesign.rejected')}}</el-tag>
              <el-tag v-else-if="scope.row.firstStatus === 'End'" type="success">{{$t('graduationDesign.passed')}}</el-tag>
              <el-tag v-else-if="scope.row.firstStatus === 'Recall'" type="info">{{$t('graduationDesign.recall')}}</el-tag>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.reviewStatus')" min-width="100" v-else>
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 'WaitCommit'" type="info">{{$t('graduationDesign.draft')}}</el-tag>
              <el-tag v-else-if="scope.row.status === 'Process'" type="info">{{$t('graduationDesign.pendingReview')}}</el-tag>
              <el-tag v-else-if="scope.row.status === 'Reject'" type="danger">{{$t('graduationDesign.rejected')}}</el-tag>
              <el-tag v-else-if="scope.row.status === 'End'" type="success">{{$t('graduationDesign.passed')}}</el-tag>
              <el-tag v-else-if="scope.row.status === 'Recall'" type="info">{{$t('graduationDesign.recall')}}</el-tag>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.operation')" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="onReview(scope.row)" v-if="(scope.row.firstStatus === 'Process' && role === 'Tutor') || (scope.row.status === 'Process' && role === 'Designated')">{{$t('graduationDesign.review')}}</el-button>
              <el-button type="text" @click="onView(scope.row)">{{$t('graduationDesign.view')}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
      </el-card>
    </div>

    <div v-if="indexKey === 'VIEW' || indexKey === 'REVIEW'">
      <!--查看-->
      <OpeningReportInfo :actionType="actionType" :roleId="roleId" :stuType="stuType" :progressData="progressData" :openingReportForm="openingReportForm" :studentForm="studentForm" @opening-report-pass="onPass" @opening-report-reject="onReject" @opening-report-cancel="onCancel" :dataInfo="dataInfo"></OpeningReportInfo>
    </div>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/openingReport"
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
  name: 'openingReport',
  props: {
    url: {
      type: String,
      default: ''
    },
    role: {
      type: String,
      default: ''
    },
    indexKey: {
      type: String,
      default: 'MAIN'
    },
    dataInfo:{
      type: Object,
      default: {}
    },
    actionType: {
      type: String,
      default: ''
    },
    idTip: {
      type: String,
      default: ''
    },

  },
  data() {
    return {
      api: API,
      getList: '/api/designservice/defenseGroup/list',
      queryForm: {
        grade: '',
        collegeId: '',
        subjectId: '',
        projectName: '',
        status: '',
        teacherNum: '',
        firstStatus: '',
        authId: localStorage.getItem('activeAuthId')
      },
      loading: false,
      //indexKey: 'MAIN',
      source: {
        studentColleges: [], // 行政学院
        collegeOptions: [], // 学院
        subjectOptions: [], // 专业
        // 审核状态
        statusOptions: [{
          label: "待审核",
          value: "Process"
        }, {
          label: "已驳回",
          value: "Reject"
        }, {
          label: "已通过",
          value: "End"
        }]
      },
      breadPath: {
        label: this.$t('graduationDesign.reviewOpeningReport'),
        key: "MAIN",
        children: [
          {
            key: "VIEW",
            label: this.$t('graduationDesign.viewOpeningReport')
          },
          {
            key: "REVIEW",
            label: this.$t('graduationDesign.reviewOpeningReport')
          }
        ]
      },
      selectedData: [], // 勾选的列表数据
      dialogVisible: false,
      //actionType: "",
      roleId: 1,
      stuType: '',
      openingReportForm: {},
      studentForm: {},
      subjectDetail: {}, // 课题信息
      progressData: [], //审核进度列表
      identity: ''
    };
  },
  created() {
    if(this.dataInfo&&this.dataInfo.no){
      this.roleId=3;
    }else{
      this.roleId = this.role === "Tutor" ? 1 : 2;
    }
  },
  mounted() {
    if(this.dataInfo&&this.dataInfo.no){
      console.log(this.dataInfo,'dataInfo')
      this.studentForm=this.dataInfo.content;
      this.openingReportForm=this.dataInfo.content;
      this.progressData=this.dataInfo.listApproveHistory;
    }
    this.queryForm.grade = new Date().getFullYear() + '';
    this.getCollege();
    this.searchList();
    this.identity = this.getIdentity();
    tools.initAllCollege(this.source.studentColleges);
  },
  methods: {
    searchList() {
      if (this.role === "Tutor") {
        this.queryForm.firstStatus = this.queryForm.status;
      }
      this.$refs.reviewReportTable.search(this.queryForm);
    },
    reset() {
      this.queryForm = {
        grade: '',
        collegeId: '',
        subjectId: '',
        projectName: '',
        status: '',
        teacherNum: '',
        firstStatus: '',
        authId: localStorage.getItem('activeAuthId')
      };
      this.source.subjectOptions = [];
      this.queryForm.grade = new Date().getFullYear() + '';
      this.searchList();
    },
    handleSelectChange(val) {
      this.selectedData = val;
    },
    handleGradeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.collegeId) {
        this.handleCollegeChange(this.queryForm.collegeId);
      }
    },
    getIdentity() {
      let identity = "";
      switch (this.role) {
        case 'Academic':
          identity = "1"; // 学院教务员
          break;
        case 'Tutor':
          identity = "2"; // 导师
          break;
        case 'Designated':
          identity = "3"; // 指定审核人
          break;
        default:
          break;
      }
      return identity;
    },
    // 查学院
    getCollege() {
      this.api.getCollege().then(res => {
        this.source.collegeOptions = res;
      });
    },
    // 选择年份和学院查专业
    handleCollegeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.grade) {
        const params = {
          grade: this.queryForm.grade,
          college: val
        };
        this.api.getSubject(params).then(res => {
          this.source.subjectOptions = res.data;
        }).catch();
      }
    },
    // 查审核进度
    getReviewProgress(flowNo) {
      this.api.getProgress(flowNo).then(res => {
        this.progressData = res.data.listApproveHistory;
      }).catch();
    },
    // 查学生信息
    getStudentInfo(params) {
      return this.api.getStudentInfo(params).then(res => {
        return res.data;
      });
    },
    // 查学生文科理科（文科：1，理科：2）
    getStudentType(params = {}) {
      return this.api.getStuArtsOrSciences(params).then(({ data }) => {
        return data;
      });
    },
    // 审核
    async onReview(row) {
      this.actionType = "REVIEW";
      const params = {
        studentId: row.studentId
      };
      this.studentForm = (await this.getStudentInfo(params)) || {};
      this.stuType = await this.getStudentType(this.studentForm);
      this.api.getReportDetail(row.id).then(({ data }) => {
        this.indexKey = 'REVIEW';
        this.openingReportForm = { ...data };
        this.openingReportForm.projectName = row.projectName;
        this.openingReportForm.subtitleName = row.subtitleName;
        this.progressData = [];
        if (row.flowNo) {
          this.getReviewProgress(row.flowNo);
        }
      });
    },
    // 查看
    async onView(row) {
      this.actionType = "REVIEW_VIEW";
      const params = {
        studentId: row.studentId
      };
      this.studentForm = (await this.getStudentInfo(params)) || {};
      this.stuType = await this.getStudentType(this.studentForm);
      this.api.getReportDetail(row.id).then(({ data }) => {
        this.indexKey = 'VIEW';
        this.openingReportForm = { ...data };
        this.openingReportForm.projectName = row.projectName;
        this.openingReportForm.subtitleName = row.subtitleName;
        this.progressData = [];
        if (row.flowNo) {
          this.getReviewProgress(row.flowNo);
        }
      });
    },
    // 通过/驳回提交
    handleSubmit(data, type) {
      this.api.approval(data).then(res => {
        this.indexKey = "MAIN";
        this.$message.success((type === "End") ? this.$t('graduationDesign.passed') : this.$t('graduationDesign.rejected'));
        this.searchList();
      }).catch(() => { });
    },
    // 通过开题报告
    onPass(data, type) {
      this.handleSubmit(data, type);
    },
    // 驳回开题报告
    onReject(data, type) {
      this.handleSubmit(data, type);
    },
    onCancel() {
      this.indexKey = "MAIN";
      this.searchList();
    },
    // 指定审核人
    onDesignated() {
      if (!this.selectedData.length) {
        this.$eduAlert(this.$t('graduationDesign.pleaseSelectData'), this.$t('graduationDesign.prompt'));
        return false;
      }
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.designatedDialog.reset();
      });
    },
    // 指定审核人 提交
    designatedSubmit(data) {
      this.api.designated(data).then(res => {
        this.$message.success(this.$t('graduationDesign.submitSuccess'));
        this.dialogVisible = false;
        this.searchList();
      }).catch();
    },
    // 指定审核人 取消
    designatedCancel() {
      this.dialogVisible = false;
    },
    // 导出PDF
    onExport() {
      const params = {
        identity: this.identity,
        condition: this.queryForm,
        selectList: this.selectedData
      };
      this.newKey = "";
      this.api.export(params).then(res => {
        tools.downloadZip(res.data.key,
          `/api/designservice/openReport/exportReport/${res.data.data.newKey}`,
          `审核开题报告（${this.getIdentity() === "1" ? "学院教务员" : (this.getIdentity() === "2" ? "导师" : "指定审核人")}).zip`,
          this.api.getFileExportStatus, this
        );
        /*if (res.code == 200) {
          this.delayRequest(res.data.key);
          this.newKey = res.data.data.newKey;
        }*/
      });
    },
    getExportStatus(key) {
      return this.api.getFileExportStatus(key).then(res => {
        return res;
      }).catch(err => {
        this.loading = false;
      });
    },
    // 查文件导出状态，等待导出
    async delayRequest(key) {
      this.loading = true;
      await new Promise(resolve => setTimeout(resolve, 3000));
      const resData = await this.getExportStatus(key);
      if (resData.code === 200 && resData.data.status) {
        this.loading = false;
        window.open("/api/designservice/openReport/exportReport/" + this.newKey);
      } else {
        this.delayRequest(key);
      }
    }
  },
  components: {
    OpeningReportInfo: () => import('./openingReportInfo'),
    DesignatedDialog: () => import('../../topicSelectMgt/reviewSubject/components/designatedDialog')
  }
}
</script>
<style lang="scss" scoped>
.opening-report {
    .search-item {
        width: 100%;
    }
}
</style>
